package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.entity.dto.TokenUserInfoDto;
import com.easychat.entity.dto.UserContactSearchResultDto;
import com.easychat.entity.enums.*;
import com.easychat.entity.po.UserContact;
import com.easychat.entity.po.UserInfo;
import com.easychat.entity.query.UserContactApplyQuery;
import com.easychat.entity.query.UserContactQuery;
import com.easychat.entity.query.UserInfoQuery;
import com.easychat.entity.vo.PaginationResultVO;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.entity.vo.UserInfoVo;
import com.easychat.exception.BusinessException;
import com.easychat.service.GetOnlineService;
import com.easychat.service.UserContactApplyService;
import com.easychat.service.UserContactService;
import com.easychat.service.UserInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @Author Dongdong
 * @注释 用户联系人
 */
@RestController
@RequestMapping("/contact")
public class UserContactController extends ABaseController {

    @Resource
    private UserContactService userContactService;
    @Resource
    private UserContactApplyService userContactApplyService;
    @Resource
    private UserInfoService userInfoService;


    /**
     * 搜索用户
     *
     * @param contactId 联系人ID
     * @return
     */
    @PostMapping("/search")
    @GlobalInterceptor
    public ResponseVO search(@NotEmpty String contactId,
                             HttpServletRequest request) {
        if (contactId == null) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        UserContactSearchResultDto userContactSearchResultDto = userContactService.searchContact(tokenUserInfo.getUserId(), contactId);
        return getSuccessResponseVO(userContactSearchResultDto);
    }

    /**
     * 添加联系人 / 加入群组
     *
     * @param contactId 联系人ID  ：用户or群ID
     * @param applyInfo 申请信息
     * @param request   请求
     * @return
     */
    @PostMapping("/applyAdd")
    @GlobalInterceptor
    public ResponseVO applyAdd(@NotEmpty String contactId,
                               String applyInfo,
                               HttpServletRequest request) {

        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        Integer joinType = userContactApplyService.applyAdd(tokenUserInfo, contactId, applyInfo);
        return getSuccessResponseVO(joinType);
    }

    /**
     * 获取申请列表
     *
     * @param pageNo  页码
     * @param request
     * @return
     */
    @RequestMapping("/loadApply")
    @GlobalInterceptor
    public ResponseVO loadApply(Integer pageNo, HttpServletRequest request) {

        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        UserContactApplyQuery userContactApplyQuery = new UserContactApplyQuery();
        userContactApplyQuery.setOrderBy("last_apply_time desc");//按申请时间倒序
        userContactApplyQuery.setPageNo(pageNo);
        userContactApplyQuery.setReceiveUserId(tokenUserInfo.getUserId());
        userContactApplyQuery.setPageSize(PageSize.SIZE15.getSize());
        userContactApplyQuery.setQueryContactInfo(true);//开启展示名称

        PaginationResultVO resultVo = userContactApplyService.findListByPage(userContactApplyQuery);

        return getSuccessResponseVO(resultVo);
    }

    /**
     * 接收者处理申请
     *
     * @param applyId 申请ID
     * @param status  处理后的状态
     * @param request
     * @return
     */
    @RequestMapping("/dealWithApply")
    @GlobalInterceptor
    public ResponseVO dealWithApply(@NotNull Integer applyId,
                                    @NotNull Integer status,
                                    HttpServletRequest request) {

        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        userContactApplyService.dealWithApply(tokenUserInfo.getUserId(), applyId, status);

        return getSuccessResponseVO(null);
    }

    /**
     * 获取联系人列表
     *
     * @param contactType 联系人类型 群/好友
     * @param request
     * @return
     */
    @RequestMapping("/loadContact")
    @GlobalInterceptor
    public ResponseVO loadContact(@NotEmpty String contactType,
                                  HttpServletRequest request) {
        UserContactTypeEnum userContactTypeEnum = UserContactTypeEnum.getByName(contactType);
        if (userContactTypeEnum == null) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        UserContactQuery userContactQuery = new UserContactQuery();
        userContactQuery.setContactType(userContactTypeEnum.getType());
        userContactQuery.setUserId(tokenUserInfo.getUserId());

        //如果是群
        if (UserContactTypeEnum.GROUP.equals(userContactTypeEnum)) {
            //联合表去查群的信息
            userContactQuery.setQueryGroupInfo(true);
            userContactQuery.setExcludeMyGroup(true);
            /*
            -- 加载出某人的所有为‘群’的联系人的详细信息
            select  g.*
            from user_contact c  join group_info g on c.contact_id=g.group_id
            where c.contact_type=1 and c.user_id='U57106584291'
             */
        } else if (UserContactTypeEnum.USER.equals(userContactTypeEnum)) {
            /*
            -- 加载出某人的所有为好友的联系人的详细信息
            select  u.*
            from user_info u left join user_contact c on c.contact_id=u.user_id
            where c.contact_type=0 and c.user_id='U42545344603'
             */
            userContactQuery.setQueryContactUserInfo(true);

        }
        userContactQuery.setOrderBy("last_update_time desc");
        //被群拉黑，被群删除，正常 状态都可以看得到群聊，设置查询条件
        userContactQuery.setStatusArray(new Integer[]{
                        UserContactStatusEnum.FRIEND.getCode(),
                        UserContactStatusEnum.DELETE_BE.getCode(),
                        UserContactStatusEnum.BLACK_BE.getCode()
                }
        );
        List<UserContact> userContactList = userContactService.findListByParam(userContactQuery);

        return getSuccessResponseVO(userContactList);
    }


    /**
     * 好友列表中，点击头像显示出的名片信息
     *
     * @param contactId 好友ID
     * @param request
     * @return
     */
    @RequestMapping("/getContactInfo")
    @GlobalInterceptor
    public ResponseVO getContactInfo(@NotEmpty String contactId,
                                     HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        UserInfoVo userInfoVo = userInfoService.getContactInfo(contactId);
        userInfoVo.setContactStatus(UserContactStatusEnum.NOT_FRIEND.getCode());
        UserContact usercontact = userContactService.getUserContactByUserIdAndContactId(tokenUserInfo.getUserId(), contactId);
        if (usercontact != null) {
            userInfoVo.setContactStatus(UserContactStatusEnum.FRIEND.getCode());
        }
        return getSuccessResponseVO(userInfoVo);
    }


    /**
     * 点击好友头像，显示出好友的详细信息
     *
     * @param contactId 好友ID
     * @param request
     * @return
     */
    @RequestMapping("/getContactUserInfo")
    @GlobalInterceptor
    public ResponseVO getContactUserInfo(@NotEmpty String contactId,
                                         HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        UserInfoVo userInfoVo = userInfoService.getContactInfo(contactId);
        return getSuccessResponseVO(userInfoVo);
    }

    /**
     * 删除好友
     *
     * @param contactId 被删除的好友ID
     * @param request
     * @return null
     */
    @RequestMapping("/delContact")
    @GlobalInterceptor
    public ResponseVO delContact(@NotNull String contactId,
                                 HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        userContactService.delContact(tokenUserInfo.getUserId(), contactId, UserContactStatusEnum.DELETE);
        return getSuccessResponseVO("删除成功");
    }

    /**
     * 拉黑对方
     *
     * @param contactId 被拉黑的好友ID
     * @param request
     * @return null
     */
    @RequestMapping("/addContact2BlackList")
    @GlobalInterceptor
    public ResponseVO addContact2BlackList(@NotNull String contactId,
                                           HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        userContactService.delContact(tokenUserInfo.getUserId(), contactId, UserContactStatusEnum.BLACK);
        return getSuccessResponseVO("拉黑成功");
    }

    @Resource
    private GetOnlineService getOnlineService;

    @RequestMapping("/push/friend")
    @GlobalInterceptor
    public ResponseVO push(HttpServletRequest request,boolean isOnline){
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        getOnlineService.pushFriend(tokenUserInfo,isOnline);
        return getSuccessResponseVO(null);
    }


}
